import { appConfig, BEFORE_INITIAL, emitter, qs } from '@idmy/core'
import { AES, enc, MD5, mode, pad } from 'crypto-js'

let AES_SECRET = null
emitter.on(BEFORE_INITIAL, () => {
  AES_SECRET = enc.Utf8.parse(appConfig.security.secret)
})
const AES_OPTIONS = { mode: mode.ECB, padding: pad.Pkcs7 }

export function aesEncrypt(ciphertext) {
  return AES.encrypt(ciphertext, AES_SECRET, AES_OPTIONS).toString()
}

export function getSign(unsigned, append = {}) {
  const str = qs.stringify(unsigned) + '&key=' + appConfig.security.secret
  const sign = MD5(decodeURIComponent(str)).toString().toUpperCase()
  return { ...unsigned, ...append, sign }
}
